import { useEffect, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { getArticles, deleteArticle } from '@/store/actions';
import { Link, useHistory } from 'react-router-dom';
import {
  Card,
  Breadcrumb,
  Form,
  Button,
  Radio,
  DatePicker,
  Table,
  Tag,
  Space,
  Modal,
} from 'antd';

import {
  EditOutlined,
  DeleteOutlined,
  ExclamationCircleOutlined,
} from '@ant-design/icons';

import Channel from '@/components/Channel';

import 'moment/locale/zh-cn';
import locale from 'antd/es/date-picker/locale/zh_CN';
import styles from './index.module.scss';

import imgError from '@/assets/error.png';

// const { Option } = Select;
const { RangePicker } = DatePicker;
const { confirm } = Modal;

// 优化文章状态的处理
const articleStatus = {
  0: { color: 'yellow', text: '草稿' },
  1: { color: '#ccc', text: '待审核' },
  2: { color: 'green', text: '审核通过' },
  3: { color: 'red', text: '审核失败' },
};

const Article = () => {
  // 查询条件状态
  const [filter, setFilter] = useState({
    status: -1, // 文章状态
    channelId: -1, // 频道
    dateStart: '', // 开始日期
    dateEnd: '', // 截止日期
    page: 1, // 页码
    pageSize: 10, // 每页条数
  });

  const history = useHistory();

  const dispatch = useDispatch(); // dispatch
  // const channels = useSelector((state) => state.article.channels); // 频道数据
  const list = useSelector((state) => state.article.list); // 文章列表
  const total = useSelector((state) => state.article.total); // 总数
  // 组件首次渲染
  // useEffect(() => {
  //   dispatch(getChannels());
  // }, [dispatch]);
  // 筛选数据
  useEffect(() => {
    dispatch(getArticles(filter));
  }, [filter, dispatch]);

  // 提交筛选
  const onFinish = (values) => {
    const { status, channelId, date } = values;
    setFilter({ ...filter, status });
    // 处理频道
    if (channelId !== undefined) {
      setFilter({ ...filter, channelId });
    }
    // 日期范围
    if (typeof date !== 'undefined' && date !== null) {
      setFilter({
        ...filter,
        dateStart: date[0].format('YYYY-MM-DD HH:mm:ss'),
        dateEnd: date[1].format('YYYY-MM-DD HH:mm:ss'),
      });
    }
  };
  // 分页数据获取
  const changePage = (page, pageSize) => {
    setFilter({ ...filter, page, pageSize });
  };

  // 删除文章
  const delArticle = (id) => {
    confirm({
      title: '温馨提示',
      icon: <ExclamationCircleOutlined />,
      content: '此操作将永久删除该文章, 是否继续?',
      onOk: () => {
        console.log(id);
        dispatch(deleteArticle(id, filter));
      },
    });
  };

  const columns = [
    {
      title: '封面',
      dataIndex: 'cover',
      render: (cover) => {
        return <img src={cover || imgError} width={200} height={150} alt="" />;
      },
    },
    {
      title: '标题',
      dataIndex: 'title',
      width: 220,
    },
    {
      title: '状态',
      dataIndex: 'status',
      render: (data) => {
        // 方式一：使用 if-else 判断每一种情况
        // if (data === 0) {
        //   return <Tag color="yellow">草稿</Tag>
        // } else if (data === 1) {
        //   return <Tag color="#ccc">待审核</Tag>
        // } else if (data === 2) {
        //   return <Tag color="green">审核通过</Tag>
        // } else if (data === 3) {
        //   return <Tag color="red">审核失败</Tag>
        // }

        // 方式二：使用对象属性的访问，替代了 原来的 if-else 或 switch-case 判断
        const tagData = articleStatus[data];
        return <Tag color={tagData.color}>{tagData.text}</Tag>;
      },
    },
    {
      title: '发布时间',
      dataIndex: 'pubdate',
    },
    {
      title: '阅读数',
      dataIndex: 'read_count',
    },
    {
      title: '评论数',
      dataIndex: 'comment_count',
    },
    {
      title: '点赞数',
      dataIndex: 'like_count',
    },
    {
      title: '操作',
      render: (data) => {
        return (
          <Space size="middle">
            <Button
              type="primary"
              shape="circle"
              icon={<EditOutlined />}
              onClick={() => history.push(`/home/publish/${data.id}`)}
            />
            <Button
              type="primary"
              danger
              shape="circle"
              icon={<DeleteOutlined />}
              onClick={() => delArticle(data.id)}
            />
          </Space>
        );
      },
    },
  ];

  return (
    <div className={styles.root}>
      <Card
        title={
          <Breadcrumb separator=">">
            <Breadcrumb.Item>
              <Link to="/home/index">首页</Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>内容管理</Breadcrumb.Item>
          </Breadcrumb>
        }
        style={{ marginBottom: 20 }}
      >
        <Form initialValues={{ status: -1 }} onFinish={onFinish}>
          <Form.Item label="状态" name="status">
            <Radio.Group>
              <Radio value={-1}>全部</Radio>
              <Radio value={0}>草稿</Radio>
              <Radio value={1}>待审核</Radio>
              <Radio value={2}>审核通过</Radio>
              <Radio value={3}>审核失败</Radio>
            </Radio.Group>
          </Form.Item>

          <Form.Item label="频道" name="channelId">
            <Channel />
            {/* <Select placeholder="请选择文章频道" style={{ width: 120 }}>
              {channels.map((item) => (
                <Option key={item.id} value={item.id}>
                  {item.name}
                </Option>
              ))}
            </Select> */}
          </Form.Item>

          <Form.Item label="日期" name="date">
            <RangePicker locale={locale}></RangePicker>
          </Form.Item>

          <Form.Item>
            <Button type="primary" htmlType="submit">
              筛选
            </Button>
          </Form.Item>
        </Form>
      </Card>

      {/* 列表 */}
      <Card title={`根据筛选条件共查询到 ${total} 条结果：`}>
        <Table
          columns={columns}
          dataSource={list}
          rowKey="id"
          pagination={{
            current: filter.page,
            pageSize: filter.pageSize,
            total: total,
            showSizeChanger: true,
            position: ['bottomCenter'],
            onChange: changePage,
          }}
        />
      </Card>
    </div>
  );
};

export default Article;
